﻿using APPWG4806.Back.Entry;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace APPWG4806
{
    public partial class MaterialQueryForm : DevExpress.XtraEditors.XtraForm
    {
        private Form132 form132;

        public int pageSize = 15;

        public int pageIndex = 1;

        public int pageCount;

        public string MaterialTextValue = "";

        public string sqlStr = "SELECT [l].[MaterialId], [t].[MaterialNo], [l].[WorkStationSeq]," +
                " [l].[WorkStationName], [l].[WorkStationVersion], [l].[LastWorkStation], " +
                "[l].[IsPrint], [l].[IsCheck], [l].[BatchQty], [t].[MaterialSpec], [l].[IdIndex], " +
                "[l1].[WorkStationTypeName], [t].[Color], [t].[OutDiameter] ";

        public string SqlWhere = " FROM [LH_WorkStation] AS [l] OUTER APPLY " +
                "( SELECT [l0].[Color], [l0].[MaterialNo], [l0].[MaterialSpec], [l0].[OutDiameter]" +
                " FROM [LH_Material] AS [l0]" +
                " WHERE [l].[MaterialId] = [l0].[ID]) AS [t]" +
                " LEFT JOIN [LH_WorkStationType] AS [l1] ON [l].[WorkStationTypeId] = [l1].[ID]" +
                " WHERE [l].[Condtion] = CAST(0 AS bit) and [t].[MaterialNo] LIKE '%";
        public string SqlWhere2 =
                "%' ORDER BY [l].[MaterialId], [l].[WorkStationVersion], [l].[WorkStationSeq]";

        string newSqlWhere = "";
        public MaterialQueryForm(Form132 form132)
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            this.form132 = form132;
        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            // 设置提示文本
            Material_TB.Text = "请输入物料号";
            Material_TB.ForeColor = SystemColors.GrayText;
            try
            {
                BindPageGridList(sqlStr + SqlWhere + MaterialTextValue + SqlWhere2);
            }
            catch (Exception)
            {
                return;
            }

            gridView1.Columns["MaterialId"].Caption = "物料序号";
            gridView1.Columns["MaterialNo"].Caption = "物料编号";
            gridView1.Columns["WorkStationSeq"].Caption = "工序序号";
            gridView1.Columns["WorkStationName"].Caption = "工序名称";
            gridView1.Columns["WorkStationVersion"].Caption = "版本";
            gridView1.Columns["LastWorkStation"].Caption = "最后工序";
            gridView1.Columns["IsPrint"].Caption = "是否打印";
            gridView1.Columns["IsCheck"].Caption = "是否电测";
            gridView1.Columns["BatchQty"].Caption = "批次数量";
            gridView1.Columns["MaterialSpec"].Caption = "物料规格";
            gridView1.Columns["IdIndex"].Caption = "工序编号";
            gridView1.Columns["WorkStationTypeName"].Caption = "工序类型";
            gridView1.Columns["Color"].Caption = "颜色";
            gridView1.Columns["OutDiameter"].Caption = "外径";

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ColumnAutoWidth = false;
        }

        /// <summary>
        /// 绑定分页控件和GridControl数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        public void BindPageGridList(string strWhere)
        {
            dataNavigator1.Buttons.CustomButtons[0].Enabled = true;
            dataNavigator1.Buttons.CustomButtons[1].Enabled = true;
            dataNavigator1.Buttons.CustomButtons[2].Enabled = true;
            dataNavigator1.Buttons.CustomButtons[3].Enabled = true;

            int startIndex = (pageIndex - 1) * pageSize + 1;

            int endIndex = pageIndex * pageSize;

            // 获取总页数
            //newSqlWhere = SqlWhere + MaterialTextValue + SqlWhere2;
            //Match match = Regex.Match(newSqlWhere, "(?i)order\\s+by[^order]*", RegexOptions.RightToLeft);
            //string instr = newSqlWhere.Remove(match.Index);
            //int row = DatabaseHelper.GetRecordCount("select count(1) "+instr);
            int row = 0;
            try
            {
                row = int.Parse(HttpHelp.GetData("http://localhost:9081/LH_ListApi/GetMaterialWorkStationByMaterialNoALL?materialNo=" + MaterialTextValue, null));
            }
            catch (Exception)
            {
                MessageBox.Show("API连接失败");

                throw new Exception();
            }
            if (row % pageSize > 0)
            {
                pageCount = row / pageSize + 1;
            }
            else
            {
                pageCount = row / pageSize;
            }

            if (pageIndex == 1)
            {
                dataNavigator1.Buttons.CustomButtons[0].Enabled = false;
                dataNavigator1.Buttons.CustomButtons[1].Enabled = false;
            }

            if (pageCount == pageIndex)
            {
                endIndex = row;
                dataNavigator1.Buttons.CustomButtons[2].Enabled = false;
                dataNavigator1.Buttons.CustomButtons[3].Enabled = false;
            }
            #region 数据库获取数据
            //  数据库获取分页数据列表来更新页面
            //DataTable dt = DatabaseHelper.ExecuteQuery(strWhere,  pageIndex, pageSize,null);
            #endregion

            string urlStr = "http://localhost:9081/LH_ListApi/GetMaterialWorkStationByMaterialNo?materialNo=" + MaterialTextValue;
            if (pageSize > 0 && pageIndex > 0)
            {
                urlStr = urlStr + "&pageIndex=" + pageIndex + "&pageSize=" + pageSize;
            }
            string json = "";
            try
            {
                json = HttpHelp.GetData(urlStr, null);
            }
            catch (Exception)
            {
                MessageBox.Show("API连接失败");
                throw;
            }
            List<MaterialEntry> entries = JsonConvert.DeserializeObject<List<MaterialEntry>>(json);
            gridControl1.DataSource = entries;
            dataNavigator1.DataSource = entries;
            dataNavigator1.DataSource = gridView1.DataSource;
            dataNavigator1.TextStringFormat = string.Format("第 {0}页，共{1}页", pageIndex, pageCount);
        }

        /// <summary>
        /// 按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataNavigator1_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            ShowEvent("ButtonClick", e.Button);
        }

        /// <summary>
        /// 分页事件处理
        /// </summary>
        /// <param name="v"></param>
        /// <param name="button"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowEvent(string v, NavigatorButtonBase button)
        {
            NavigatorCustomButton btn = (NavigatorCustomButton)button;
            string type = btn.Tag.ToString();
            if (type == "首页")
            {
                pageIndex = 1;
            }
            if (type == "下一页")
            {
                pageIndex++;
            }
            if (type == "末页")
            {
                pageIndex = pageCount;
            }
            if (type == "上一页")
            {
                pageIndex--;
            }
            BindPageGridList(sqlStr + SqlWhere + MaterialTextValue + SqlWhere2);
        }


        /// <summary>
        /// 返回选中数据按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void returnData_BT_Click(object sender, EventArgs e)
        {
            int index = gridView1.GetFocusedDataSourceRowIndex();
            if (index >= 0)
            {
                MaterialEntry material = null;
                material = new MaterialEntry
                {
                    MaterialId = (int)gridView1.GetRowCellValue(index, "MaterialId"),
                    MaterialNo = gridView1.GetRowCellValue(index, "MaterialNo") == null?null:gridView1.GetRowCellValue(index, "MaterialNo").ToString(),
                    WorkStationSeq = (int)gridView1.GetRowCellValue(index, "WorkStationSeq"),
                    WorkStationName = gridView1.GetRowCellValue(index, "WorkStationName")==null?null: gridView1.GetRowCellValue(index, "WorkStationName").ToString(),
                    WorkStationVersion = gridView1.GetRowCellValue(index, "WorkStationVersion") == null ? null : gridView1.GetRowCellValue(index, "WorkStationVersion").ToString(),
                    LastWorkStation = (bool)gridView1.GetRowCellValue(index, "LastWorkStation"),
                    IsPrint = (bool)gridView1.GetRowCellValue(index, "IsPrint"),
                    IsCheck = (bool)gridView1.GetRowCellValue(index, "IsCheck"),
                    BatchQty = (int)gridView1.GetRowCellValue(index, "BatchQty"),
                    MaterialSpec = gridView1.GetRowCellValue(index, "MaterialSpec") == null ? null : gridView1.GetRowCellValue(index, "MaterialSpec").ToString(),
                    IdIndex = gridView1.GetRowCellValue(index, "IdIndex") == null ? null : gridView1.GetRowCellValue(index, "IdIndex").ToString(),
                    WorkStationTypeName = gridView1.GetRowCellValue(index, "WorkStationTypeName") == null ? null : gridView1.GetRowCellValue(index, "WorkStationTypeName").ToString(),
                    Color = gridView1.GetRowCellValue(index, "Color") == null ? null : gridView1.GetRowCellValue(index, "Color").ToString(),
                    OutDiameter = gridView1.GetRowCellValue(index, "OutDiameter") == null ? null : gridView1.GetRowCellValue(index, "OutDiameter").ToString(),
                };
                form132.Data = material;
                this.Close();
            }
            else
            {
                return;
            }
        }

        private void Material_TB_Enter(object sender, EventArgs e)
        {
            // 用户点击TextBox时的操作
            if (Material_TB.Text == "请输入物料号")
            {
                Material_TB.Text = "";
                Material_TB.ForeColor = SystemColors.WindowText;
            }
        }

        private void Material_TB_Leave(object sender, EventArgs e)
        {
            // 用户离开TextBox时的操作
            if (Material_TB.Text == "")
            {
                Material_TB.Text = "请输入物料号";
                Material_TB.ForeColor = SystemColors.GrayText;
            }
        }

        private void Search_BT_Click(object sender, EventArgs e)
        {
            #region 远程获取数据
            // 远程调用链接
            string materialNum = Material_TB.Text.Trim();
            if (!string.IsNullOrWhiteSpace(materialNum) && !materialNum.Equals("请输入物料号"))
            {
                MaterialTextValue = Material_TB.Text.Trim();
            }
            else
            {
                MaterialTextValue = "";
            }
            pageIndex = 1;
            BindPageGridList("");
            #endregion
            #region 从数据库获取数据
            //Match match = Regex.Match(SqlWhere + MaterialTextValue + SqlWhere2, "(?i)order\\s+by[^order]*", RegexOptions.RightToLeft);

            //if (match.Success)
            //{
            //    newSqlWhere= sqlStr + SqlWhere + MaterialTextValue + SqlWhere2;
            //    // 获取"ORDER BY"之前的部分
            //    string partBeforeLastOrderBy = newSqlWhere.Substring(0, match.Index);

            //    // 获取"ORDER BY"及其之后的整个字符串
            //    string partAfterLastOrderBy = newSqlWhere.Substring(match.Index);

            //    // 插入新的字符，例如 "NEW STUFF "
            //    string materialNum = Material_TB.Text.Trim();
            //    if (!string.IsNullOrWhiteSpace(materialNum)&&!materialNum.Equals("请输入物料号"))
            //    {
            //        MaterialTextValue = materialNum;
            //        newSqlWhere = sqlStr + SqlWhere + MaterialTextValue + SqlWhere2;
            //        pageIndex = 1;
            //        BindPageGridList(newSqlWhere);
            //    }
            //}
            //else
            //{
            //    Console.WriteLine("The query does not contain 'ORDER BY'.");
            //}
            #endregion
        }
    }
}